package logic

import (
	"context"
	"fmt"
	"register/model/cache"
	"register/model/mysql"

	"register/registerRpc/internal/svc"
	"register/registerRpc/registerRpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ForgetUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewForgetUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ForgetUserLogic {
	return &ForgetUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ForgetUserLogic) ForgetUser(in *registerRpc.ForgetUserRequest) (*registerRpc.ForgetUserResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	mysql.DB.Debug().Where("account=?", in.Account).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("该用户不存在,请重新输入")
	}

	if user.Password == in.Password {
		return nil, fmt.Errorf("原密码与旧密码一致,请重新输入")
	}

	if in.Password != in.NewPassword {
		return nil, fmt.Errorf("新密码与确认新密码不一致,请重新输入")
	}

	cacheKey, _ := cache.Rdb.Get(l.ctx, "SmsKey"+in.Account).Result()
	if in.SmsCaptcha != cacheKey {
		return nil, fmt.Errorf("短信验证码错误,请重新输入")
	}

	captcha, _ := cache.Rdb.Get(l.ctx, "captchaKey"+in.Account).Result()
	if in.Captcha != captcha {
		return nil, fmt.Errorf("图片验证码错误,请重新输入")
	}

	user.Password = in.Password
	mysql.DB.Debug().Updates(&user)
	return &registerRpc.ForgetUserResponse{
		UserId: int64(user.ID),
	}, nil
}
